using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.AI;

public class ZombieController : MonoBehaviour
{
    private Animator animator;
    private Transform player;
    private NavMeshAgent navMeshAgent;
    private SpriteRenderer spriteRenderer;

    public const float MaxHP = 100.0f;
    public float CurrentHP { get; set; }
    [SerializeField] float vision = 5.0f;

    void Awake()
    {
        this.animator = GetComponent<Animator>();
        this.player = GameObject.Find(Defines.Player).GetComponent<Transform>();
        this.navMeshAgent = GetComponent<NavMeshAgent>();
        this.spriteRenderer = GetComponent<SpriteRenderer>();
    }

    void Start()
    {
        this.CurrentHP = MaxHP;
    }

    void Update()
    {
        if (this.CurrentHP <= 0)
            return;

        var distance = Vector3.Distance(transform.position, player.position);
        if (distance < this.vision)
        {
            this.animator.SetBool(Defines.Move, true);

            if (distance < 2)
            {
                this.navMeshAgent.isStopped = true;
                this.animator.SetTrigger("Attack");
            }
            else
            {
                this.navMeshAgent.isStopped = false;
                this.navMeshAgent.SetDestination(this.player.position);
            }
        }
        else
        {
            this.animator.SetBool(Defines.Move, false);
        }
    }

    public void Damage(float point)
    {
        if (this.CurrentHP <= 0)
            return;
            
        this.animator.CrossFade("Damage", 0);
        this.CurrentHP -= point;

        if (this.CurrentHP <= 0)
        {
            Die();
        }
    }

    private void Die()
    {
        this.animator.SetTrigger("Die");
        Invoke(nameof(Destroy), 5);
    }

    private void Destroy()
    {
        Destroy(gameObject);
    }
}
